package com.sip.stream.gbstack;

import android.content.Context;
import android.util.Log;

import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.gosuncn.gbstack.JniGS28181Agent;
import com.sip.stream.gbstack.Model.GB28181RTPAction;
import com.sip.stream.gbstack.Model.GS28181AlarmNotify;
import com.sip.stream.gbstack.Model.GS28181AlarmNotifyConfig;
import com.sip.stream.gbstack.Model.GS28181AudioParams;
import com.sip.stream.gbstack.Model.GS28181CatalogNotifyConfig;
import com.sip.stream.gbstack.Model.GS28181ExpiredNotifyConfig;
import com.sip.stream.gbstack.Model.GS28181PosNotify;
import com.sip.stream.gbstack.Model.GS28181PosNotifyConfig;
import com.sip.stream.gbstack.Model.GS28181VideoParams;
import com.sip.stream.gbstack.RespondModel.GS28181DeviceCatalogRespondModel;
import com.sip.stream.gbstack.RespondModel.GS28181DeviceInfoRespondModel;
import com.sip.stream.gbstack.RespondModel.GS28181DeviceStatusRespondModel;
import com.sip.stream.media.ZFYMediaManager;

import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class GS28181SDK {
    private static final String TAG = "GS28181SDK";

    private static final String SAVE_CONFIG = "SAVE_CONFIG";

    private static GS28181SDK shareInstance;
    private GS28181AlwaysListener alwaysListener;
    protected GS28181SDKConfig config;
    private WeakReference<Context> contextWeakReference;
    private NewSendHelper sendHelper;
    private GS28181StreamNotifyListener streamNotifyListener;
    private int sendCommunicationErrorCounter = 0;
    private AtomicInteger initSDKCode = null;
    protected GS28181SDKStatus status = new GS28181SDKStatus();

    private GS28181SDK() {}

    public static GS28181SDK getInstance() {
        if (shareInstance == null) {
            synchronized (GS28181SDK.class) {
                shareInstance = new GS28181SDK();
            }
        }
        return shareInstance;
    }

    public void init(Context context) {
        this.contextWeakReference = new WeakReference<>(context);
    }

    public String queryNotifyJsonCallback(int i, String str, String str2) {
        return str2;
    }


    public int initSDK() {
        if (this.initSDKCode != null && this.initSDKCode.get() == 0) {
            return this.initSDKCode.get();
        }
        int initSDK = JniGS28181Agent.getInstance().initSDK(getConfig().getDeviceGBCode(), getConfig().getLocalIP(), getConfig().getLocalPort(), getConfig().getCmdTranType(), getConfig().getGB28181Version());
        this.initSDKCode = new AtomicInteger(initSDK);
        return initSDK;
    }

    public int unInitSDK() {
        int uninitSDK = JniGS28181Agent.getInstance().uninitSDK();
        this.initSDKCode = null;
        return uninitSDK;
    }

    public int postRegister(GS28181AlwaysListener gS28181AlwaysListener) {
        this.alwaysListener = gS28181AlwaysListener;
        int register = JniGS28181Agent.getInstance().register(getConfig().getServerGBCode(), getConfig().getServerIP(), getConfig().getServerPort(), getConfig().getRegistertime(), getConfig().getAccount(), getConfig().getPassword());
        if (register == 0) {
            getInstance().getStatus().setRegisted(true);
        }
        return register;
    }

    public void postUnregister(GS28181SDKCallBack gS28181SDKCallBack) {
        int i;
        Log.w(TAG, "postUnregister");
        getInstance().getStatus().setRegisted(false);
        getInstance().setAlwaysListener(null);
        getInstance().setStreamNotifyListener(null);
        boolean z = (JniGS28181Agent.getInstance().unregister() == 0) & true;
        try {
            i = unInitSDK();
            Log.i(TAG, "uninitSDK" + i);
        } catch (Exception unused) {
            i = -1;
        }
        if (!z && gS28181SDKCallBack != null) {
            gS28181SDKCallBack.onComplete(new GS28181Result(i, RetCode.getErrorMsg(i)));
        } else if (gS28181SDKCallBack != null) {
            Log.e(TAG, "JniGS28181Agent.getInstance().unregister() failed code = " + i);
            gS28181SDKCallBack.onComplete(new GS28181Result(0, RetCode.getErrorMsg(i)));
        }
    }

    public void handleQueryNotifyCallback(int code, long sessionHandle, String str, String str2) {
        GS28181AlwaysListener gS28181AlwaysListener;
        if (code == 1)
        {
            if (this.alwaysListener != null)
            {
                this.alwaysListener.onQueryDeviceInfo(sessionHandle);
            }
        } else if (code != 2)
        {
            if (code == 3 && (gS28181AlwaysListener = this.alwaysListener) != null)
            {
                gS28181AlwaysListener.onQueryDeviceCatalog(sessionHandle);
            }
        } else
        {
            if (this.alwaysListener != null)
            {
                this.alwaysListener.onQueryStatus(sessionHandle);
            }
        }
    }

    public void postRespondQueryDeviceInfo(GS28181DeviceInfoRespondModel gS28181DeviceInfoRespondModel, GS28181SDKCallBack gS28181SDKCallBack) {
        int respondQueryDeviceInfo = JniGS28181Agent.getInstance().respondQueryDeviceInfo(gS28181DeviceInfoRespondModel.getSessionHandle(), gS28181DeviceInfoRespondModel.getDeviceGBCode(), gS28181DeviceInfoRespondModel.getDeviceName(), gS28181DeviceInfoRespondModel.getManufacturer(), gS28181DeviceInfoRespondModel.getModel(), gS28181DeviceInfoRespondModel.getFirmware(), gS28181DeviceInfoRespondModel.getChannel());
        if (gS28181SDKCallBack != null) {
            gS28181SDKCallBack.onComplete(new GS28181Result(respondQueryDeviceInfo, RetCode.getErrorMsg(respondQueryDeviceInfo)));
        }
    }

    public void postRespondQueryDeviceStatus(GS28181DeviceStatusRespondModel gS28181DeviceStatusRespondModel, GS28181SDKCallBack gS28181SDKCallBack) {
        int respondQueryDeviceStatus = JniGS28181Agent.getInstance().respondQueryDeviceStatus(gS28181DeviceStatusRespondModel.getSessionHandle(), gS28181DeviceStatusRespondModel.getDeviceGBCode(), getFormatDateString(new Date()), gS28181DeviceStatusRespondModel.getErrReason(), gS28181DeviceStatusRespondModel.isEncode(), gS28181DeviceStatusRespondModel.isRecord(), gS28181DeviceStatusRespondModel.isOnline(), gS28181DeviceStatusRespondModel.isStatusOK());
        if (gS28181SDKCallBack != null) {
            gS28181SDKCallBack.onComplete(new GS28181Result(respondQueryDeviceStatus, RetCode.getErrorMsg(respondQueryDeviceStatus)));
        }
    }

    public void postRespondQueryDeviceCatalog(GS28181DeviceCatalogRespondModel gS28181DeviceCatalogRespondModel) {
        Log.i(TAG, "respondQueryDeviceCatalog2 " + JniGS28181Agent.getInstance().respondQueryDeviceCatalog2(new Gson().toJson(getConfig()), gS28181DeviceCatalogRespondModel.getLongitude(), gS28181DeviceCatalogRespondModel.getLatitude()));
    }

    public void getSDKInfo(GS28181SDKCallBack<String> gS28181SDKCallBack) {
        if (gS28181SDKCallBack != null) {
            gS28181SDKCallBack.onComplete(new GS28181Result<>(JniGS28181Agent.getInstance().getSDKInfo()));
        }
    }

    public void postAlarmNotify(GS28181AlarmNotify gS28181AlarmNotify, GS28181SDKCallBack gS28181SDKCallBack) {
        int alarmNotify = JniGS28181Agent.getInstance().alarmNotify(getConfig().getDeviceGBCode(), gS28181AlarmNotify.priority, gS28181AlarmNotify.method, gS28181AlarmNotify.time, gS28181AlarmNotify.content, gS28181AlarmNotify.alarmType, gS28181AlarmNotify.eventType, gS28181AlarmNotify.longitude, gS28181AlarmNotify.latitude, gS28181AlarmNotify.extension);
        if (gS28181SDKCallBack != null) {
            gS28181SDKCallBack.onComplete(new GS28181Result(alarmNotify, RetCode.getErrorMsg(alarmNotify)));
        }
    }

    public int postCatalogNotifyToSub(int subId) {
        return JniGS28181Agent.getInstance().catalogNotifyToSub(subId);
    }

    public void postTransDatas(String data, GS28181SDKCallBack gS28181SDKCallBack) {
        int transDatas = JniGS28181Agent.getInstance().transDatas(data);
        if (gS28181SDKCallBack != null) {
            gS28181SDKCallBack.onComplete(new GS28181Result(transDatas, RetCode.getErrorMsg(transDatas)));
        }
    }

    public int postTransDataGateway(String data) {
        return JniGS28181Agent.getInstance().transDataGateway(data);
    }

    public int respondTransData(boolean status, String json, int type) {
        return JniGS28181Agent.getInstance().respondTransData(status, json, type);
    }

    public void postHeartBeat(GS28181SDKCallBack gS28181SDKCallBack) {
        int sendHeartBeat = JniGS28181Agent.getInstance().sendHeartBeat();
        if (gS28181SDKCallBack != null) {
            gS28181SDKCallBack.onComplete(new GS28181Result(sendHeartBeat));
        }
    }


    public int keepaliveRregister() {
        return JniGS28181Agent.getInstance().keepaliveRregister();
    }

    public String getFormatDateString(Date date) {
        return new SimpleDateFormat(GS28181SDKConfig.GS28181SDK_DATE_FORMAT, Locale.CHINA).format(date);
    }

    public void handlerJniSubscribeNotify(int code, String message, String data) {
        switch (code) {
            case 8:
                Single.just(data).observeOn(Schedulers.newThread()).delay(100L, TimeUnit.MILLISECONDS).map(new Function() {
                    @Override
                    public Object apply(Object obj) {
                        String asString = JsonParser.parseString((String) obj).getAsJsonObject().get("czSourceID").getAsString();
                        return asString;
                    }
                }).doOnError(new Consumer() {
                    @Override
                    public void accept(Object obj) {
                        ((Throwable) obj).printStackTrace();
                    }
                }).onErrorReturnItem(getConfig().getServerGBCode()).subscribe(new SingleObserver<String>() {
                    @Override
                    public void onError(Throwable th) {
                    }

                    @Override
                    public void onSubscribe(Disposable disposable) {
                    }

                    @Override
                    public void onSuccess(String str3) {
                        JniGS28181Agent.getInstance().inviteAudioPlayRequest(str3, GS28181SDK.this.getConfig().getStreamTranType());
                    }
                });
                return;
            case 9:
                Log.i(TAG, "SUBSCRIBE_NOTIFY_CATASUBS " + data);
                if (this.alwaysListener != null) {
                    this.alwaysListener.onSubscribeCatalogNotify(new GS28181CatalogNotifyConfig(data));
                    return;
                }
                return;
            case 10:
                if (this.alwaysListener != null) {
                    this.alwaysListener.onSubscribeAlarmNotify(new GS28181AlarmNotifyConfig(data));
                    return;
                }
                return;
            case 11:
                if (this.alwaysListener != null) {
                    this.alwaysListener.onSubscribePosNotify(new GS28181PosNotifyConfig(data));
                    return;
                }
                return;
            case 12:
                if (this.alwaysListener != null) {
                    this.alwaysListener.onSubscribeExpiredNotify(new GS28181ExpiredNotifyConfig(data));
                    return;
                }
                return;
            default:
                return;
        }
    }

    public void inviteVideoPlayRequest(String srcDeviceID) {
        JniGS28181Agent.getInstance().inviteVideoPlayRequest(srcDeviceID, getConfig().getStreamTranType());
    }

    public void postAlarmNotifyToSub(int alarmSubId, GS28181AlarmNotify gS28181AlarmNotify, GS28181SDKCallBack gS28181SDKCallBack) {
        String gbCode = gS28181AlarmNotify.getGbCode();
        if (gbCode == null || gbCode.length() == 0) {
            gbCode = getConfig().getDeviceGBCode();
        }
        int alarmNotifyToSub = JniGS28181Agent.getInstance().alarmNotifyToSub(alarmSubId, gbCode, gS28181AlarmNotify.priority, gS28181AlarmNotify.method, gS28181AlarmNotify.time, gS28181AlarmNotify.content, gS28181AlarmNotify.alarmType, gS28181AlarmNotify.eventType, gS28181AlarmNotify.longitude, gS28181AlarmNotify.latitude, gS28181AlarmNotify.extension);
        this.status.setLatitudeLongitude(gS28181AlarmNotify.latitude, gS28181AlarmNotify.longitude);
        if (gS28181SDKCallBack != null) {
            gS28181SDKCallBack.onComplete(new GS28181Result(alarmNotifyToSub, RetCode.getErrorMsg(alarmNotifyToSub)));
        }
    }

    public int postMobilePosNotifyToSub(int posSubId, GS28181PosNotify gS28181PosNotify) {
        String gbCode = gS28181PosNotify.getGbCode();
        if (gbCode == null || gbCode.length() == 0) {
            gbCode = getConfig().getDeviceGBCode();
        }
        return JniGS28181Agent.getInstance().mobilePosNotifyToSub(posSubId, gbCode, gS28181PosNotify.getTime(), gS28181PosNotify.getLongitude(), gS28181PosNotify.getLatitude(), gS28181PosNotify.getSpeed(), gS28181PosNotify.getDirection(), gS28181PosNotify.getAltitude());
    }

    public int onTransDataNotify(String json, int code) {
        GS28181AlwaysListener gS28181AlwaysListener = this.alwaysListener;
        if (gS28181AlwaysListener != null) {
            return gS28181AlwaysListener.onTransDataNotify(json, code);
        }
        return 200;
    }

    public void setAlwaysListener(GS28181AlwaysListener gS28181AlwaysListener) {
        this.alwaysListener = gS28181AlwaysListener;
    }

    public void setStreamNotifyListener(GS28181StreamNotifyListener gS28181StreamNotifyListener) {
        this.streamNotifyListener = gS28181StreamNotifyListener;
    }

    public synchronized void startVideoStream()
    {
        if (this.streamNotifyListener != null) {
            this.streamNotifyListener.startVideoStream();
        }
        if (this.sendHelper == null) {
            NewSendHelper newSendHelper = new NewSendHelper(new SendHelper.SendHelperListener() {
                @Override
                public void setRemotePerformanceLevel(int i) {
                    if (GS28181SDK.this.streamNotifyListener != null) {
                        GS28181SDK.this.streamNotifyListener.onVideoStreamPerformanceLevel(i);
                    }
                }

                @Override
                public void forceStop() {
                    JniGS28181Agent.getInstance().forceStopRTP(true);
                    GS28181SDK gs28181sdk = GS28181SDK.this;
                    gs28181sdk.handleStreamNotifyCallback(5, gs28181sdk.getConfig().getServerGBCode(), "{\"streamtype\":\"video\",\"action\":5}");
                }
            });
            this.sendHelper = newSendHelper;
            newSendHelper.startSend();
        }
    }

    public void stopVideoStream() {
        if (this.sendHelper != null) {
            this.sendHelper.release();
            this.sendHelper = null;
        }
        if (this.streamNotifyListener != null) {
            this.streamNotifyListener.stopVideoStream();
        }
    }

    public void postInputVideoStream(ByteBuffer byteBuffer, int i, long j) {
        if (this.sendHelper != null) {
            this.sendHelper.addFrame(byteBuffer, i, j);
        }
    }

    public void postInputAudioStream(byte[] bArr, long j) {
        if (JniGS28181Agent.getInstance().inputAudioStream(bArr, j - 1000) != 10000) {
            int i = this.sendCommunicationErrorCounter + 1;
            this.sendCommunicationErrorCounter = i;
            if (i > 1000) {
                JniGS28181Agent.getInstance().forceStopRTP(false);
                handleStreamNotifyCallback(5, getConfig().getServerGBCode(), "{\"streamtype\":\"audio\",\"action\":5}");
                return;
            }
            return;
        }
        this.sendCommunicationErrorCounter = 0;
    }

    public void stopStreaming() {
        JniGS28181Agent.getInstance().forceStopRTP(true);
        JniGS28181Agent.getInstance().forceStopRTP(false);
        JniGS28181Agent.getInstance().forceStopInviteVoiceTalk();
    }

    public void stopStreaming(int type) {
        if (type == 1) {
            JniGS28181Agent.getInstance().forceStopInviteVoiceTalk();
        } else if (type == 2) {
            JniGS28181Agent.getInstance().forceStopRTP(false);
        } else {
            JniGS28181Agent.getInstance().forceStopRTP(true);
        }
    }

    public void stopInviteVoiceTalk() {
        JniGS28181Agent.getInstance().forceStopInviteVoiceTalk();
    }

    public void postVideoParams(int videoHeight, int videoFps, int videoBitrate, GS28181SDKCallBack gS28181SDKCallBack) {
        GS28181VideoParams videoParams = getConfig().getVideoParams();
        int i4 = videoHeight > 1000 ? 6 : 5;
        Log.d(TAG, "postVideoParams ppi:" + i4 + " frameRate:" + videoFps);
        int videoParams2 = JniGS28181Agent.getInstance().setVideoParams(videoParams.videoCodeID, i4, videoFps, videoParams.rateType, videoBitrate);
        if (gS28181SDKCallBack != null) {
            gS28181SDKCallBack.onComplete(new GS28181Result(videoParams2, RetCode.getErrorMsg(videoParams2)));
        }
    }

    public void postAudioParams(GS28181SDKCallBack gS28181SDKCallBack) {
        GS28181AudioParams audioParams = getConfig().getAudioParams();
        int audioParams2 = JniGS28181Agent.getInstance().setAudioParams(audioParams.audioCodeID, audioParams.sample, audioParams.bitRate);
        if (gS28181SDKCallBack != null) {
            gS28181SDKCallBack.onComplete(new GS28181Result(audioParams2, RetCode.getErrorMsg(audioParams2)));
        }
    }

    public void syncDevTime(String time) {
        if (time == null) {
            return;
        }
        try {
            Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);
            if (parse.getTime() <= 0 || this.alwaysListener == null) {
                return;
            }
            Log.i(TAG, "syncDevTime: " + parse.toLocaleString() + " time: " + parse.getTime());
            this.alwaysListener.syncDevTime(parse.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void handleStreamNotifyCallback(int code, String str, String json) {
        GB28181RTPAction gb28181RTPAction = null;
        Log.i(TAG, "json: " + json);
        if (json != null)
        {
            gb28181RTPAction = new Gson().fromJson(json, GB28181RTPAction.class);
            String streamtype = gb28181RTPAction.getStreamtype();
            if (gb28181RTPAction != null) {
                code = gb28181RTPAction.getAction();
                streamtype = gb28181RTPAction.getStreamtype();
            }
            Log.i(TAG, "tType " + code + " streamtype " + streamtype);
            if (code != 1)
            {
                if (ZFYMediaManager.ACTION_AUDIO.equalsIgnoreCase(streamtype))
                {
                    if (this.streamNotifyListener != null)
                    {
                        this.streamNotifyListener.startAudioStream();
                    }
                    this.sendCommunicationErrorCounter = 0;
                    return;
                } else if ("inviteVoiceTalk".equalsIgnoreCase(streamtype))
                {
                    if (this.streamNotifyListener != null)
                    {
                        this.streamNotifyListener.startInviteVoiceTalk();
                        return;
                    }
                    return;
                } else {
                    startVideoStream();
                    return;
                }
            } else if (code == 4) {
                if (this.streamNotifyListener != null)
                {
                    Log.i(TAG, "STREAM_NOTIFY_AUDIO");
                    this.streamNotifyListener.startAudioStream();
                }
                this.sendCommunicationErrorCounter = 0;
                return;
            } else if (code != 5)
            {
                return;
            } else {
                if (ZFYMediaManager.ACTION_AUDIO.equalsIgnoreCase(streamtype))
                {
                    if (this.streamNotifyListener != null) {
                        this.streamNotifyListener.stopAudioStream();
                    }
                    this.sendCommunicationErrorCounter = 0;
                    return;
                } else if (ZFYMediaManager.ACTION_VIDEO.equalsIgnoreCase(streamtype))
                {
                    if (this.streamNotifyListener != null) {
                        this.streamNotifyListener.stopVideoStream();
                        return;
                    }
                    return;
                } else if ("inviteVoiceTalk".equalsIgnoreCase(streamtype))
                {
                    if (this.streamNotifyListener != null)
                    {
                        this.streamNotifyListener.byeInviteVoiceTalk();
                        return;
                    }
                    return;
                } else {
                    if (this.streamNotifyListener != null) {
                        this.streamNotifyListener.stopStream();
                        return;
                    }
                    return;
                }
            }
        }
        gb28181RTPAction = null;
        if (gb28181RTPAction != null) {
            Log.i(TAG, "tType " + code + " streamtype " + gb28181RTPAction.getStreamtype());
        }
    }

    public void receiveStreamCallBack(int code, byte[] data, long j) {
        if (this.streamNotifyListener == null || data == null || data.length <= 0) {
            return;
        }
        this.streamNotifyListener.receiveAudioStream(data, j);
    }

    public void receiveVideoStreamCallBack(int code, byte[] data, long j) {
        if (this.streamNotifyListener == null || data == null || data.length <= 0) {
            return;
        }
        this.streamNotifyListener.receiveVideoStream(data, j);
    }

    public void rtpStreamCallBack(int code) {
        if (this.streamNotifyListener != null) {
            this.streamNotifyListener.onError(code, RetCode.getErrorMsg(code));
        }
    }

    protected void postErrorBack(int code) {
        if (this.alwaysListener != null) {
            this.alwaysListener.onError(code, RetCode.getErrorMsg(code));
        }
    }

    public void setConfig(GS28181SDKConfig gS28181SDKConfig) {
        this.config = gS28181SDKConfig;
        JniGS28181Agent.getInstance().logSwitch(true);
    }

    public GS28181SDKStatus getStatus() {
        return this.status;
    }

    public Context getContext() {
        if (this.contextWeakReference != null) {
            return this.contextWeakReference.get();
        }
        return null;
    }

    public GS28181SDKConfig getConfig() {
        if (this.config == null) {
            if (getContext() == null) {
                Log.w(TAG, "getConfig when context not init");
                return new GS28181SDKConfig();
            }
            String configJSON = SPUtils.getInstance().getString(SAVE_CONFIG,null);
            if (configJSON != null) {
                this.config = new Gson().fromJson(configJSON,  GS28181SDKConfig.class);
            }
            if (this.config == null) {
                return new GS28181SDKConfig();
            }
        }
        return this.config;
    }

    public void saveConfig() {
        saveConfig(this.config, getContext());
    }

    public static void saveConfig(GS28181SDKConfig gS28181SDKConfig, Context context) {
        if (gS28181SDKConfig == null || context == null) {
            return;
        }
        String json = new Gson().toJson(gS28181SDKConfig);
        Log.d(TAG, "save config " + json);
        SPUtils.getInstance().put(SAVE_CONFIG,json);
    }

    public void setNetStatus(String mobileNetworkStr, int wifiSignalLevel) {
        if (this.sendHelper != null) {
            this.sendHelper.setNetStatus(mobileNetworkStr, wifiSignalLevel);
        }
    }

    public void responseTransData(String json, int type) {
        JniGS28181Agent.getInstance().respondTransData(true, json, type);
    }

    public void releaseTransDataSession(int sessionHandle) {
        JniGS28181Agent.getInstance().releaseTransDataSession(sessionHandle);
    }

    public int generateXmlSn() {
        return JniGS28181Agent.getInstance().generateXmlSn();
    }

    public int transdataMessage(String json) {
        return JniGS28181Agent.getInstance().transdataMessage(json);
    }
}
